package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.PeriodRecord;
import com.imut.lagain.service.IPeriodRecordService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.*;
import jakarta.validation.Valid;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生理期记录控制器
 */
@RestController
@RequestMapping("/api/period-records")
@RequiredArgsConstructor
@Validated
public class PeriodRecordController {
    private static final Logger log = LoggerFactory.getLogger(PeriodRecordController.class);

    private final IPeriodRecordService periodRecordService;
    private final JwtUtil jwtUtil;

    /**
     * 创建生理期记录
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createPeriodRecord(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody CreatePeriodRecordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            PeriodRecord record = new PeriodRecord();
            record.setUserId(userId);
            record.setStartDate(request.getStartDate());
            record.setEndDate(request.getEndDate());
            record.setCycleLength(request.getCycleLength());
            record.setSymptoms(request.getSymptoms());
            record.setNotes(request.getNotes());
            
            boolean success = periodRecordService.save(record);
            if (success) {
                response.put("success", true);
                response.put("message", "生理期记录创建成功");
                response.put("data", record);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "生理期记录创建失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("创建生理期记录失败", e);
            response.put("success", false);
            response.put("message", "创建生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取生理期记录详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getPeriodRecord(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            PeriodRecord record = periodRecordService.getById(id);
            if (record == null) {
                response.put("success", false);
                response.put("message", "生理期记录不存在");
                return ResponseEntity.notFound().build();
            }
            
            if (!record.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权访问此记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            response.put("success", true);
            response.put("data", record);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取生理期记录失败", e);
            response.put("success", false);
            response.put("message", "获取生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新生理期记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updatePeriodRecord(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id,
            @Valid @RequestBody UpdatePeriodRecordRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            PeriodRecord record = periodRecordService.getById(id);
            if (record == null) {
                response.put("success", false);
                response.put("message", "生理期记录不存在");
                return ResponseEntity.notFound().build();
            }
            
            if (!record.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权修改此记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            record.setStartDate(request.getStartDate());
            record.setEndDate(request.getEndDate());
            record.setCycleLength(request.getCycleLength());
            record.setSymptoms(request.getSymptoms());
            record.setNotes(request.getNotes());
            
            boolean success = periodRecordService.updateById(record);
            if (success) {
                response.put("success", true);
                response.put("message", "生理期记录更新成功");
                response.put("data", record);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "生理期记录更新失败");
                return ResponseEntity.internalServerError().body(response);
            }
            
        } catch (Exception e) {
            log.error("更新生理期记录失败", e);
            response.put("success", false);
            response.put("message", "更新生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除生理期记录
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deletePeriodRecord(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            PeriodRecord record = periodRecordService.getById(id);
            if (record == null) {
                response.put("success", false);
                response.put("message", "生理期记录不存在");
                return ResponseEntity.notFound().build();
            }
            
            if (!record.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "无权删除此记录");
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
            }
            
            boolean success = periodRecordService.removeById(id);
            response.put("success", success);
            response.put("message", success ? "生理期记录删除成功" : "生理期记录删除失败");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("删除生理期记录失败", e);
            response.put("success", false);
            response.put("message", "删除生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取生理期记录列表（分页）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getPeriodRecords(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Page<PeriodRecord> pageParam = new Page<>(page, size);
            IPage<PeriodRecord> recordPage = periodRecordService.findByUserId(userId, pageParam);
            
            response.put("success", true);
            response.put("data", recordPage);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取生理期记录列表失败", e);
            response.put("success", false);
            response.put("message", "获取生理期记录列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 根据日期范围获取生理期记录
     */
    @GetMapping("/date-range")
    public ResponseEntity<Map<String, Object>> getPeriodRecordsByDateRange(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<PeriodRecord> records = periodRecordService.findByUserIdAndDateRange(userId, startDate, endDate);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("根据日期范围获取生理期记录失败", e);
            response.put("success", false);
            response.put("message", "根据日期范围获取生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取最近的生理期记录
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentPeriodRecords(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "5") @Min(1) @Max(20) int size) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<PeriodRecord> records = periodRecordService.findRecentByUserId(userId, size);
            response.put("success", true);
            response.put("data", records);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取最近生理期记录失败", e);
            response.put("success", false);
            response.put("message", "获取最近生理期记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 创建生理期记录请求类
     */
    @Data
    public static class CreatePeriodRecordRequest {
        @NotNull(message = "开始日期不能为空")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private LocalDate startDate;
        
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private LocalDate endDate;
        
        @Min(value = 10, message = "周期长度至少为10天")
        @Max(value = 90, message = "周期长度最多为90天")
        private Integer cycleLength = 28;
        
        private String symptoms;

        private String notes;

        public LocalDate getStartDate() {
            return startDate;
        }

        public LocalDate getEndDate() {
            return endDate;
        }

        public Integer getCycleLength() {
            return cycleLength;
        }

        public String getSymptoms() {
            return symptoms;
        }

        public String getNotes() {
            return notes;
        }
    }

    /**
     * 更新生理期记录请求类
     */
    @Data
    public static class UpdatePeriodRecordRequest {
        @NotNull(message = "开始日期不能为空")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private LocalDate startDate;

        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private LocalDate endDate;

        @Min(value = 10, message = "周期长度至少为10天")
        @Max(value = 90, message = "周期长度最多为90天")
        private Integer cycleLength;

        private String symptoms;

        private String notes;

        public LocalDate getStartDate() {
            return startDate;
        }

        public LocalDate getEndDate() {
            return endDate;
        }

        public Integer getCycleLength() {
            return cycleLength;
        }

        public String getSymptoms() {
            return symptoms;
        }

        public String getNotes() {
            return notes;
        }
    }
}